import React, { PropTypes, Component } from 'react'
import fetch from 'isomorphic-fetch'
import { Link } from 'react-router'

import Table from './Table'
import NavLink from './NavLink'
import style from './addStore.css'

import { myAjax,ROOTURL_MALL } from '../publicAPI/publicAPI'

class MallStoreM extends Component {
	constructor (props, context) {
		super(props, context);

		this.state = {
				delete: false,
				deleteId: -1,
				dataList: []
		}; // 初始化状态

		this.start = 0;
		this.limit = 10;
		this.requestAll = false; //判断是否请求所有数据
	}

	componentWillMount() {
		this.getlist();
	}

	getlist() {
	    var url = ROOTURL_MALL + 'kabuy/pickshop/search.api';
	    fetch(url, {
	        method: 'POST',
	        mode: "cors",
	        body: JSON.stringify({
	            "where": {
	                dd: [
	                    ["eq", false]
	                ]
	            },
	            start: this.start,
	            limit: this.limit
	        })
	    }).then(response => {
	        if (response.ok) {
	            return response.json()
	        } else {
						  throw new Error('获取门店失败')
					}
	    }).then((data) => {
					console.log(data)
					if (data.length < this.limit) {
							this.requestAll = true
					} else {
							this.requestAll = false
					}
					this.setState({dataList: data})
			}).catch(function(error) {
	        console.log('Request failed', error);
	    });

	}

	handleDelete(id){
		this.setState({
			delete: !this.state.delete,
			deleteId : id
		})
	}

	handleStoreDelete(){
		var url = ROOTURL_MALL + 'kabuy/pickshop/instance.api?id='+this.state.deleteId;
		console.log(this.state.deleteId)
		this.setState({
			delete: !this.state.delete
		});
		fetch(url, {
			method : 'delete',
			// mode : 'no-cors',
			body: JSON.stringify({})
		}).then(res=>{
			if(res.ok){
				res.json().then(data=>{
					location=location
				})
			}
		});
	}

	getMinute(hour) {
		var m = parseInt((hour - parseInt(parseInt(hour / 3600000) * 3600000)) / 60000);
		var fm = m + '';
		if (m < 10) {
			fm = "0" + m;
		}
		return fm;
	}

	getTime(tmOpen, tmClose){
		return (parseInt(tmOpen / 3600000) + ':' + this.getMinute(tmOpen) + '-' + parseInt(tmClose / 3600000) + ':' + this.getMinute(tmClose))
	}
	handlePageClick(e) {//1为下一页，2为上一页
        const _buttonValue = e.target.value

        if(_buttonValue == 1) {
            this.start = this.start + this.limit

        } else {
            this.start = this.start - this.limit
        }
        this.getlist()
    }

	//render thead
	tHead() {
		var data = [
			{name: "提取点名字"},
			{name: "提取点位置"},
			{name: "开店时间"},
			{name: "操作"}
		];
		const _headArr = [];
		const _width = {
			"0" : "25%",
			"1" : "25%",
			"2" : "25%",
			"3" : "25%",

		};
		//_headArr.push(<th style={{width:'5%'}} role="1" key='' onClick={(e) => this.handleSelect(e)}></th>)
		_headArr.push(data.map((item, index) => <th style={{width: _width[index]}} role="1" key={index}>{item.name}</th>))
		return _headArr;
	}

	tBody() {
		var array=new Array();
		var _this=this;
		var i;
		console.log("datalist",this.state.dataList)
		 for(i=0;i<_this.state.dataList.length;i++){
      		if(this.state.dataList[i].dd==false){
				            array[i]= (<tr key={this.state.dataList[i].id}>
							<td>{_this.state.dataList[i].name}</td>
							<td>{_this.state.dataList[i].loc.split(",")[0]}</td>
							<td>{_this.state.dataList[i].tmOpen? this.getTime(this.state.dataList[i].tmOpen, this.state.dataList[i].tmClose) : null}</td>
							<td>
								<span><NavLink  to={`/MallStoreM/MallStoreEditor/${this.state.dataList[i].id}`} className="rbtn green">编辑</NavLink></span>
								<span style={{marginLeft: "15px"}}><a  className="rbtn red" onClick={this.handleDelete.bind(this,_this.state.dataList[i].id)}>删除</a></span>
							</td>
						</tr>)
        }
    }
     return array;
}

	render(){
		return (

			<div className="right-wapper ">
			    <div className="rt-wrap">
			        <h2 className="catagory">
			            <Link to={`/MallIndex`}><span className={style['cata-title']}>首页轮播图</span></Link>
			            <Link to={`/MallProductTypeM`}><span className={style['cata-title']}>商品分类管理</span></Link>
			            <Link to={`/MallProductsM`}><span className={style['cata-title']}>商品管理</span></Link>
			            <Link to={`/MallOrderM`}><span className={style['cata-title']}>订单管理</span></Link>
			            <Link to={`/MallStoreM`}><span className={style['cata-title-current']}>门店管理</span></Link>
			            <Link to={`/MallMember`}><span className={style['cata-title']}>门店店员管理</span></Link>
			            <Link to={`/MallStatisticsM`}><span className={style['cata-title']}>商城统计</span></Link>
			            <Link to={`/MallCoupon`}><span className={style['cata-title']}>优惠券管理</span></Link>
			            <Link to={`/MallStoreM/MallStoreEditor`}>
			    			<button className="add-btn" />
			    		</Link>
			        </h2>



			    	<h2 className="catagory">
			    		<span className="cata-title">门店管理</span>
			    		<button className="next" value="1" style={{display: this.requestAll ? "none" : "block"}} onClick={(e) => this.handlePageClick(e)}></button>
                        <button className="prev" value="2" style={{display: this.start ? "block" : "none"}} onClick={(e) => this.handlePageClick(e)}></button>
			    	</h2>

			    	<Table tHead={this.tHead.bind(this)()} tBody={this.tBody.bind(this)()} />
			</div>
			    { this.state.delete ?
			    	<div id={style.msgDialog}>
			    		<div className={style['msgDialog_div']}><h3 id={style['msgDialog_title']}>删除提示？</h3><p id={style['msgDialog_content']}>确认删除？</p>
			    			<div className={style['msgDialog_button']}>
			    				<button id={style['msgDialog_yes']} onClick={this.handleStoreDelete.bind(this)}>确定</button>
			    				<button id={style['msgDialog_no']} onClick={()=>this.setState({delete: !this.state.delete})}>取消</button>
			    			</div>
			    		</div>
			    	</div> : null}

			</div>
		)
	}
}


export default MallStoreM
